import './searchView.js';
import './gridView.js';
import './cardView.js';
import './formView.js';

cqjs.component('pageView', {
    template: `
    <div>
        <div v-show="['grid','card'].includes(view)">
           <searchView
                ref="search"
                :onSearch="searchCommand"></searchView>
        </div>
        <div v-if="view === 'grid'">
            <gridView
                ref="grid"
                :onCreate="createCommand"
                :onEdit="editCommand"
                :data="dataList"
                :selected="selected"
                :meta="meta"
                :arch="meta.views.grid.arch"></gridView>
        </div>
        <div v-if="view === 'card'">
            <cardView
                ref="grid"
                :onCreate="createCommand"
                :onEdit="editCommand"
                :data="dataList"
                :selected="selected"
                :meta="meta"
                :arch="meta.views.grid.arch"></gridView>
        </div>
        <div v-if="view === 'form'">
            <formView
                ref="form"
                :onCreate="createCommand"
                :onSave="saveCommand"
                :onGoBack="backCommand"
                :selected="selected"
                :meta="meta"
                :data="editData"
                :arch="meta.views.form.arch"></formView>
        </div>
    </div>
    `,
    props: ['meta'],
    data() {
        return {
            view: 'grid',
            dataList: [],
            selected: {
                data: null,
            },
            editData: {
                data: {},
                dirty: {}
            }
        }
    },
    methods: {
        async searchCommand() {
            this.dataList = await this.getTableData();
        },
        createCommand() {
            this.view = "form";
            const fields = this.$props.meta.fields;
            const data = {};
            for (const key of Object.keys(fields)) {
                if (fields[key].defaultValue !== null) {
                    data[key] = fields[key].defaultValue;
                }
            }
            this.editData.dirty = {};
            this.editData.data = data;
            this.clearFormValidate();
        },
        editCommand() {
            this.view = "form";
            this.editData.data = this.selected.data;
            this.editData.dirty = {};
            this.clearFormValidate();
        },
        clearFormValidate() {
            setTimeout(() => {
                this.$refs.form?.clearValidate();
            }, 10);
        },
        deleteCommand() {

        },
        saveCommand() {
            console.log(this.editData)
        },
        backCommand() {
            this.view = "grid";
        },
        // 获取表格数据
        getTableData() {
            return new Promise((resolve) => {
                setTimeout(() => {
                    const list = []
                    for (let i = 0; i < 20; i++) {
                        list.push({
                            f_bool: true,
                            f_char: "char1",
                            f_char_ext: "",
                            f_compute: "char1(true)",
                            f_date: "2021-01-07",
                            f_datetime: "2021-01-07 01:01:01",
                            f_float: Math.ceil(Math.random() * 100 + 1) / 10,
                            f_int: Math.ceil(Math.random() * 10 + 1),
                            f_m2o_id: null,
                            f_selection: "7",
                            f_text: "Initializing Spring DispatcherServlet 'dispatcherServlet'",
                            id: "03jh051t38tts"
                        })
                    }
                    resolve(list);
                }, 300);
            });
        },
    },
    created() {
    }
});

async function loadView() {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve({
                "resource": "<script src='./module.js'></script>",
                "auths": "@all",
                "module": "demo",
                "model": "demo.field_type",
                "present": [],
                "fields": {
                    "f_time_range": {
                        "name": "f_time_range",
                        "type": "char",
                        "label": "范围时间",
                        "help": null,
                        "readonly": false,
                        "store": true,
                        "required": false,
                        "translate": false,
                        "length": 240,
                        "trim": true,
                        "sortable": true,
                        "defaultValue": null
                    },
                    "f_multiple_image": {
                        "name": "f_multiple_image",
                        "type": "image",
                        "label": "多图片",
                        "help": "可上传多张图片，只支持附件形式保存",
                        "readonly": false,
                        "store": true,
                        "required": false,
                        "attachment": true,
                        "maxWidth": null,
                        "maxHeight": null,
                        "sortable": false,
                        "defaultValue": null
                    },
                    "f_file": {
                        "name": "f_file",
                        "type": "binary",
                        "label": "附件",
                        "help": "可配置上传单个或多个文件，以附件形式保存",
                        "readonly": false,
                        "store": true,
                        "required": false,
                        "attachment": true,
                        "sortable": false,
                        "defaultValue": null
                    },
                    "f_date": {
                        "name": "f_date",
                        "type": "date",
                        "label": "日期",
                        "help": "日期字段",
                        "readonly": false,
                        "store": true,
                        "required": true,
                        "sortable": true,
                        "defaultValue": null
                    },
                    "f_image": {
                        "name": "f_image",
                        "type": "image",
                        "label": "图片",
                        "help": "以附件形式保存，通过URL下载",
                        "readonly": false,
                        "store": true,
                        "required": false,
                        "attachment": true,
                        "maxWidth": null,
                        "maxHeight": null,
                        "sortable": false,
                        "defaultValue": null
                    },
                    "f_m2m_ids": {
                        "name": "f_m2m_ids",
                        "type": "many2many",
                        "label": "多对多",
                        "help": "多对多关联，中间表保存关系，以列表形式编辑",
                        "readonly": false,
                        "store": true,
                        "required": false,
                        "context": {},
                        "comodel": "demo.many2many",
                        "sortable": false,
                        "defaultValue": null
                    },
                    "f_bool": {
                        "name": "f_bool",
                        "type": "boolean",
                        "label": "布尔",
                        "help": "布尔字段",
                        "readonly": false,
                        "store": true,
                        "required": true,
                        "sortable": true,
                        "defaultValue": true
                    },
                    "f_file_db": {
                        "name": "f_file_db",
                        "type": "binary",
                        "label": "附件(DB)",
                        "help": "以二进制格式保存于数据库，通过Base64加载，只可上传单个文件，不建议用这种方式保存文件",
                        "readonly": false,
                        "store": true,
                        "required": false,
                        "attachment": false,
                        "sortable": false,
                        "defaultValue": null
                    },
                    "f_m2o_id": {
                        "name": "f_m2o_id",
                        "type": "many2one",
                        "label": "多对一",
                        "help": "多对一关联",
                        "readonly": false,
                        "store": true,
                        "required": false,
                        "context": {},
                        "comodel": "demo.many2one",
                        "sortable": true,
                        "defaultValue": null,
                        "link": true
                    },
                    "f_text": {
                        "name": "f_text",
                        "type": "text",
                        "label": "大文本",
                        "help": "大文本字段",
                        "readonly": false,
                        "store": true,
                        "required": false,
                        "translate": false,
                        "sortable": true,
                        "defaultValue": "I'm a text"
                    },
                    "id": {
                        "name": "id",
                        "type": "char",
                        "label": "ID",
                        "help": null,
                        "readonly": true,
                        "store": true,
                        "required": false,
                        "sortable": true,
                        "defaultValue": null
                    },
                    "f_int": {
                        "name": "f_int",
                        "type": "integer",
                        "label": "整数",
                        "help": "整数字段",
                        "readonly": false,
                        "store": true,
                        "required": false,
                        "max": null,
                        "min": null,
                        "sortable": true,
                        "defaultValue": null
                    },
                    "create_date": {
                        "name": "create_date",
                        "type": "datetime",
                        "label": "创建时间",
                        "help": null,
                        "readonly": true,
                        "store": true,
                        "required": false,
                        "sortable": true,
                        "defaultValue": null
                    },
                    "f_html": {
                        "name": "f_html",
                        "type": "html",
                        "label": "HTML",
                        "help": "HTML字段",
                        "readonly": false,
                        "store": true,
                        "required": false,
                        "translate": false,
                        "sortable": true,
                        "defaultValue": null
                    },
                    "f_big_file": {
                        "name": "f_big_file",
                        "type": "uploadModal",
                        "label": "大文件",
                        "help": null,
                        "readonly": false,
                        "store": true,
                        "required": false,
                        "attachment": true,
                        "sortable": false,
                        "defaultValue": null
                    },
                    "f_datetime": {
                        "name": "f_datetime",
                        "type": "datetime",
                        "label": "日期时间",
                        "help": "日期时间，数据库保存UTC",
                        "readonly": false,
                        "store": true,
                        "required": false,
                        "sortable": true,
                        "defaultValue": null
                    },
                    "f_compute": {
                        "name": "f_compute",
                        "type": "char",
                        "label": "计算字段",
                        "help": null,
                        "readonly": false,
                        "store": false,
                        "required": false,
                        "translate": false,
                        "length": 240,
                        "trim": true,
                        "sortable": false,
                        "defaultValue": null
                    },
                    "f_count_down": {
                        "name": "f_count_down",
                        "type": "char",
                        "label": "倒计时",
                        "help": null,
                        "readonly": false,
                        "store": true,
                        "required": false,
                        "translate": false,
                        "length": 240,
                        "trim": true,
                        "sortable": true,
                        "defaultValue": null
                    },
                    "f_float": {
                        "name": "f_float",
                        "type": "float",
                        "label": "小数",
                        "help": "小数字段，默认两位小数",
                        "readonly": false,
                        "store": true,
                        "required": false,
                        "max": null,
                        "min": null,
                        "sortable": true,
                        "defaultValue": null
                    },
                    "f_selection": {
                        "name": "f_selection",
                        "type": "selection",
                        "label": "选择",
                        "help": "选择字段",
                        "readonly": false,
                        "store": true,
                        "required": false,
                        "static": true,
                        "sortable": true,
                        "defaultValue": null,
                        "options": {
                            "1": "星期一",
                            "2": "星期二",
                            "3": "星期三",
                            "4": "星期四",
                            "5": "星期五",
                            "6": "星期六",
                            "7": "星期天"
                        }
                    },
                    "f_o2m_ids": {
                        "name": "f_o2m_ids",
                        "type": "one2many",
                        "label": "一对多",
                        "help": "一对多关联，在多的表中保存一的外键",
                        "readonly": false,
                        "store": true,
                        "required": false,
                        "context": {},
                        "inverseName": "field_id",
                        "comodel": "demo.one2many",
                        "sortable": false,
                        "defaultValue": null
                    },
                    "create_uid": {
                        "name": "create_uid",
                        "type": "many2one",
                        "label": "创建人",
                        "help": null,
                        "readonly": true,
                        "store": true,
                        "required": false,
                        "context": {},
                        "comodel": "rbac.user",
                        "sortable": true,
                        "defaultValue": null,
                        "link": true
                    },
                    "f_priority": {
                        "name": "f_priority",
                        "type": "selection",
                        "label": "评分",
                        "help": "评分字段",
                        "readonly": false,
                        "store": true,
                        "required": false,
                        "static": true,
                        "sortable": true,
                        "defaultValue": null,
                        "options": {
                            "1": "不推荐",
                            "2": "一般",
                            "3": "不错",
                            "4": "很棒",
                            "5": "极力推荐"
                        }
                    },
                    "f_radio": {
                        "name": "f_radio",
                        "type": "selection",
                        "label": "单选",
                        "help": "单选字段",
                        "readonly": false,
                        "store": true,
                        "required": false,
                        "static": true,
                        "sortable": true,
                        "defaultValue": null,
                        "options": {
                            "1": "星期一",
                            "2": "星期二",
                            "3": "星期三",
                            "4": "星期四",
                            "5": "星期五"
                        }
                    },
                    "update_date": {
                        "name": "update_date",
                        "type": "datetime",
                        "label": "修改时间",
                        "help": null,
                        "readonly": true,
                        "store": true,
                        "required": false,
                        "sortable": true,
                        "defaultValue": null
                    },
                    "f_calendar": {
                        "name": "f_calendar",
                        "type": "char",
                        "label": " ",
                        "help": null,
                        "readonly": false,
                        "store": true,
                        "required": false,
                        "translate": false,
                        "length": 240,
                        "trim": true,
                        "sortable": true,
                        "defaultValue": null
                    },
                    "f_image_db": {
                        "name": "f_image_db",
                        "type": "image",
                        "label": "图片(DB)",
                        "help": "以二进制格式保存于数据库，通过Base64加载，只可上传单张图片",
                        "readonly": false,
                        "store": true,
                        "required": false,
                        "attachment": false,
                        "maxWidth": null,
                        "maxHeight": null,
                        "sortable": false,
                        "defaultValue": null
                    },
                    "f_datetime_range_form": {
                        "name": "f_datetime_range_form",
                        "type": "char",
                        "label": "范围日期时间",
                        "help": null,
                        "readonly": false,
                        "store": true,
                        "required": false,
                        "translate": false,
                        "length": 240,
                        "trim": true,
                        "sortable": true,
                        "defaultValue": null
                    },
                    "f_char": {
                        "name": "f_char",
                        "type": "char",
                        "label": "字符",
                        "help": "字符串类型字段，默认长度240",
                        "readonly": false,
                        "store": true,
                        "required": true,
                        "translate": false,
                        "length": 240,
                        "trim": true,
                        "sortable": true,
                        "defaultValue": null
                    },
                    "f_m2m_tags": {
                        "name": "f_m2m_tags",
                        "type": "many2many",
                        "label": "多对多",
                        "help": "多对多关联，中间表保存关系，以标签tags形式编辑",
                        "readonly": false,
                        "store": true,
                        "required": false,
                        "context": {},
                        "comodel": "demo.many2many",
                        "sortable": false,
                        "defaultValue": null
                    },
                    "f_time": {
                        "name": "f_time",
                        "type": "char",
                        "label": "时间",
                        "help": null,
                        "readonly": false,
                        "store": true,
                        "required": false,
                        "translate": false,
                        "length": 240,
                        "trim": true,
                        "sortable": true,
                        "defaultValue": null
                    },
                    "update_uid": {
                        "name": "update_uid",
                        "type": "many2one",
                        "label": "修改人",
                        "help": null,
                        "readonly": true,
                        "store": true,
                        "required": false,
                        "context": {},
                        "comodel": "rbac.user",
                        "sortable": true,
                        "defaultValue": null,
                        "link": true
                    },
                    "present": {
                        "name": "present",
                        "type": "char",
                        "label": "呈现",
                        "help": null,
                        "readonly": false,
                        "store": false,
                        "required": false,
                        "translate": false,
                        "length": 240,
                        "trim": true,
                        "sortable": false,
                        "defaultValue": null
                    }
                },
                "views": {
                    "search": {
                        "view_id": "03f9ynjok8o3k",
                        "arch": "<search>\n            <field name=\"f_char\" default=\"char\"></field>\n            <field name=\"f_bool\" default=\"true\"></field>\n            <field name=\"f_date\"></field>\n            <field name=\"f_datetime\"></field>\n            <field name=\"f_date\" editor=\"date_range\"></field>\n            <field name=\"f_datetime\" editor=\"datetime_range\"></field>\n            <field name=\"f_float\" criteria=\"[&quot;|&quot;, [&quot;f_float&quot;,&quot;>=&quot;,value], [&quot;f_float&quot;,&quot;&lt;&quot;,value+3]]\"></field>\n            <field name=\"f_html\" editor=\"text\"></field>\n            <field name=\"f_int\"></field>\n            <field name=\"f_selection\"></field>\n            <field name=\"f_text\"></field>\n            <field name=\"f_radio\" editor=\"radio\"></field>\n            <field name=\"f_m2o_id\"></field>\n        </search>"
                    },
                    "form": {
                        "view_id": "03f9ynjq868e8",
                        "arch": "<form cols=\"4\">\n            <toolbar buttons=\"default\"></toolbar>\n            <field name=\"f_char\" colspan=\"2\" required=\"1\" length=\"10\" trim=\"1\"></field>\n            <field name=\"f_float\" required=\"1\" min=\"0\" max=\"5\" step=\"0.5\"></field>\n            <field name=\"f_int\" required=\"1\" min=\"0\" max=\"6\" step=\"1\" on-change=\"getDecimals\"></field>\n            <field name=\"f_priority\" editor=\"priority\"></field>\n            <field name=\"f_bool\" required=\"1\" on-change=\"getDataAction\"></field>\n            <field name=\"f_selection\" required=\"1\"></field>\n            <field name=\"f_time\" editor=\"timePicker\"></field>\n            <div style=\"grid-column: span 2; grid-row: span 1; grid-template-columns: repeat(2, 1fr)\" class=\"grid\">\n                <field name=\"f_text\" rows=\"3\"></field>\n                <field name=\"f_html\"></field>\n            </div>\n            <field name=\"f_radio\" editor=\"radio\"></field>\n            <group label=\"日期\" collapsable=\"0\" colspan=\"2\">\n                <field name=\"f_date\" required=\"1\" min=\"2020-1-1\" max=\"2201-1-1\"></field>\n                <field name=\"f_datetime\" required=\"1\" min=\"2020-1-1\" max=\"2023-1-1\"></field>\n                <field name=\"f_datetime_range_form\" editor=\"datetime_range\"></field>\n                <field name=\"f_time_range\" editor=\"time_range\"></field>\n                <field name=\"f_count_down\" editor=\"count_down\"></field>\n            </group>\n            <group label=\"关联关系\" collapsable=\"1\" colspan=\"2\">\n                <field name=\"f_m2o_id\"></field>\n                <field name=\"f_m2m_tags\" editor=\"many2many_tags\"></field>\n            </group>\n            <group label=\"图片\" collapsable=\"1\">\n                <field name=\"f_image\" width=\"100\"></field>\n                <field name=\"f_image_db\" width=\"100\"></field>\n                <field name=\"f_multiple_image\" width=\"100\" colspan=\"2\" length=\"3\" editor=\"multiple_image\"></field>\n            </group>\n            <group label=\"文件\" collapsable=\"1\">\n                <field name=\"f_file\"></field>\n                <field name=\"f_file_db\"></field>\n                <field name=\"f_big_file\" nolabel=\"1\"></field>\n            </group>\n<!--            <group label=\"预览图片\" collapsable=\"1\">-->\n<!--                <field name=\"f_preview\" editor=\"preview\" colspan=\"4\"/>-->\n<!--            </group>-->\n            <group label=\"日历\" collapsable=\"1\">\n                <field name=\"f_calendar\" editor=\"calendar\" colspan=\"4\"></field>\n            </group>\n\n            <tabs>\n                <tab label=\"一对多\">\n                    <field name=\"f_o2m_ids\" colspan=\"4\" nolabel=\"1\">\n                        <grid>\n                            <toolbar></toolbar>\n                            <field name=\"name\"></field>\n                            <field name=\"book\"></field>\n                            <edit>\n                                <field name=\"name\"></field>\n                                <field name=\"book\"></field>\n                            </edit>\n                        </grid>\n                    </field>\n                </tab>\n                <tab label=\"多对多\">\n                    <field name=\"f_m2m_ids\" colspan=\"4\" nolabel=\"1\">\n                        <grid>\n                            <toolbar></toolbar>\n                            <field name=\"name\"></field>\n                        </grid>\n                    </field>\n                </tab>\n            </tabs>\n        </form>"
                    },
                    "grid": {
                        "view_id": "03f9ynjpe7g8w",
                        "arch": "<grid>\n            <toolbar buttons=\"default|search\">\n                <div class=\"input-group\" name=\"search\" position=\"after\">\n                    <input t-enter=\"searchBy\" type=\"text\" class=\"form-control search-input\" placeholder=\"文本或大文本\" />\n                    <div class=\"input-group-append\">\n                        <button type=\"button\" class=\"btn btn-default btn-lookup\" t-click=\"searchBy\">\n                            <i class=\"fa fa-search\"></i>\n                        </button>\n                    </div>\n                </div>\n            </toolbar>\n            <field name=\"f_char\"></field>\n            <field name=\"f_bool\"></field>\n            <field name=\"f_date\"></field>\n            <field name=\"f_datetime\"></field>\n            <field name=\"f_float\"></field>\n            <field name=\"f_text\"></field>\n            <field name=\"f_int\"></field>\n            <field name=\"f_selection\"></field>\n            <field name=\"f_compute\"></field>\n            <field name=\"f_m2o_id\"></field>\n        </grid>"
                    }
                }
            });
        }, 300);
    });
}

// 加载资源
function loadResource(node) {
    return new Promise((resolve, reject) => {
        const dom = document.createElement(node.tagName);
        for (const attr of node.attributes) {
            dom.setAttribute(attr.name, attr.value);
        }
        dom.onload = resolve;
        dom.onerror = reject;
        document.querySelector("head").appendChild(dom);
    });
}

(async function () {
    const view = await loadView();
    if (view.resource) {
        const xml = cqjs.utils.parseXML('<root>' + view.resource + '</root>');
        const waits = [];
        for (const item of xml.find("root").children()) {
            waits.push(loadResource(item));
        }
        await Promise.all(waits);
    }
    cqjs.buildComponents();
    //window.meta = view;
    new Vue({
        el: '#app',
        template: '<pageView :meta="meta"/>',
        data() {
            return {
                meta: view
            }
        }
    });
})();